import { Alert, Image, ScrollView, StyleSheet, Text, View } from 'react-native';
import React, { useEffect, useState, useRef } from 'react';
import { Button, Stepper, Provider, Modal, Carousel } from '@ant-design/react-native';
import axios from 'axios';
import { router, useFocusEffect } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage';

const DescPage = () => {
  const [data, setData] = useState<any>({
    name: '',
    price: 0,
    img: [],
    detail: '',
    _id: ''
  });
  const [address, setAddress] = useState<any>({
    name: '',
    phone: '',
    address: '',
    fullAddress: ''
  });
  const [visible, setVisible] = useState(false);

  const [num, setNum] = useState(1)

  const onClose = () => setVisible(false);

  const onPopupButtonClick = () => {
    AsyncStorage.getItem('userInfo').then((res: any) => {
      if (res) {
        setVisible(true)
      } else {
        router.push('/LoginModel/login')
      }
    })
  };

  useFocusEffect(() => {
    AsyncStorage.getItem('address').then((res: any) => {
      if (res) {
        setAddress(JSON.parse(res));
      }
    });
  });

  useEffect(() => {
    getlist();
    getaddress();
  }, []);

  const getlist = async () => {
    AsyncStorage.getItem('shopInfo').then((res: any) => {
      if (res) {
        setData(JSON.parse(res));
        //console.log('1231231231', JSON.parse(res));
      }
    })
  };

  const buyItem = async () => {
    AsyncStorage.setItem('num', JSON.stringify(num))
    AsyncStorage.setItem('data', JSON.stringify(data))
    await axios.post(`http://192.168.13.227:3000/hw/addOrder`, data)
    router.push({
      pathname: '/buyPage'
    })
    onClose()
    setNum(1)
  }

  const getaddress = async () => {
    await axios.get(`http://192.168.13.227:3000/czz/getAddress`)
      .then(res => {
        res.data.data.forEach((item: any) => {
          if (item.isdefault) {
            setAddress(item);
          }
        });
      });
  };

  const [selectedIndex, setSelectedIndex] = useState(0);
  const [autoplay, setAutoplay] = useState(true);
  const carouselRef = useRef<Carousel>(null);

  const addCard = async () => {

    const { data: { code } } = await axios.post(`http://192.168.13.227:3000/czz/addcate`, {
      num: num,
      lid: data._id,
    })
    if (code === 200) {
      Alert.alert('添加成功')
      onClose()

    }
  }
  return (
    <View >
      <ScrollView >
        <View>
          <Carousel
            style={styles.wrapper}
            selectedIndex={selectedIndex}
            autoplay={autoplay}
            infinite
            ref={carouselRef}
          >
            {data.img.map((item: any) => (
              <Image key={item} source={{ uri: item }} style={{ width: '100%', height: 150 }} />
            ))}
          </Carousel>
        </View>
        <View style={{ backgroundColor: '#fff', paddingBottom: 10 }}>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', padding: 10, alignSelf: 'auto' }}>
            <Text style={{ color: 'red' }}>￥{data.price}<Text style={{ color: 'gray', fontSize: 12 }}>/1kg</Text></Text>
            <Text style={{ color: 'gray', fontSize: 12 }}>已售{Math.round(data.price)}</Text>
          </View>
          <Text style={{ paddingLeft: 10 }}>{data.name}</Text>
        </View>
        <View style={{ backgroundColor: '#fff', marginTop: 10, padding: 10 }}>
          <Text onPress={() => router.push('/AddressPage')} style={{ color: 'gray', fontSize: 10 }}>配送 <Text style={{ color: 'black' }}>发货至 {address.address}-{address.fullAddress}</Text> 点击切换</Text>
          <Text style={{ fontSize: 10, paddingTop: 10 }}><Text style={{ color: 'gray', fontSize: 10 }}>运费</Text> {data.courier}10元起</Text>
        </View>
        <View style={{ backgroundColor: '#fff', marginTop: 10, padding: 10, paddingBottom: 30 }}>
          <Text style={{ fontSize: 15 }}>商品详情</Text>
          <Text style={{ fontSize: 10 }}>{data.detail}</Text>
          <Image source={{ uri: data.img[0] }} style={{ width: '98%', height: 200 }} />
        </View>
        <Provider>
          <View style={styles.buttonContainer}>
            <Button type="primary" onPress={onPopupButtonClick}>立即购买</Button>
          </View>
          <Modal
            popup
            visible={visible}
            animationType="slide-up"
            onClose={onClose}
          >
            <View style={{ paddingVertical: 20, paddingHorizontal: 20, justifyContent: 'space-between', flexDirection: 'row' }}>
              <Image source={{ uri: data.img[0] }} style={{ width: '20%', height: 50 }} />
              <View>
                <Text>
                  {data.name}
                </Text>
                <Text style={{ color: 'red' }}>
                  ￥{data.price}/斤
                </Text>
              </View>
              <Stepper value={num} onChange={(e) => setNum(e)} min={1} />
            </View>
            <View style={{ flexDirection: 'row', justifyContent: 'space-evenly', }}>
              <Button style={{ backgroundColor: 'green' }} type="primary" onPress={addCard}>
                添加到购物车
              </Button>
              <Button type="primary" onPress={buyItem}>
                立即购买
              </Button>
            </View>
          </Modal>
        </Provider>
      </ScrollView>


    </View>
  );
};

const styles = StyleSheet.create({
  wrapper: {
    backgroundColor: '#fff',
    width: '100%',
    height: 150,
  },
  buttonContainer: {
    position: 'static',
    bottom: 0,
    left: 0,
    right: 0,
    padding: 10,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderColor: '#ddd',
  },
});

export default DescPage;